package com.example.treasure_back.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.treasure_back.service.QuestionService;
import com.example.treasure_back.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/question/{userId}")
public class QuestionWebSocket {
    public static int onlineNumber = 0;
    private static Map<String, QuestionWebSocket> clients = new ConcurrentHashMap<>();
    private Session session;
    private String userId;
    private String RivalId;

    public MyThread myThread;
    // 正在PK的用户
    private static List<String> PKing = new ArrayList<>();
    private static QuestionService questionService;
    @Autowired
    public void setQuestionService(QuestionService questionService){
        QuestionWebSocket.questionService=questionService;
    }
    private static UserService userService;
    @Autowired
    public void setUserService(UserService userService){
        QuestionWebSocket.userService=userService;
    }

    public class MyThread extends Thread{
        private volatile Boolean isOK = false;
        @Override
        public void run() {
            while (!isOK)
                findRival();
        }
        public void stopTask() {
            isOK = true;
        }
    }

    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session)
    {
        onlineNumber++;
        this.userId = userId;
        this.session = session;
        // 将新连接的用户加入列表中
        clients.put(userId, this);
        System.out.println("open"+this.userId);
        // 开始匹配， 寻找PK选手
        myThread = new MyThread();
        myThread.start();
    }
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }
    //连接关闭
    @OnClose
    public void onClose()
    {
        myThread.stopTask();
        onlineNumber--;
        clients.remove(this.userId);
        PKing.remove(this.userId);
        System.out.println("有连接关闭！ 当前在线人数" + clients.size());
    }
    //收到客户端的消息
    @OnMessage
    public void onMessage(String message, Session session)
    {
        // 拿出问题号和用户答案
        JSONObject jsonObject = JSON.parseObject(message);
        Integer id = jsonObject.getInteger("id");
        String answer = jsonObject.getString("answer");
        JSONObject response = new JSONObject();
        // 封装响应，两个个字段，是否为对方先回答rival，是否回答正确
        response.put("rival", "N");
        if(questionService.isRight(id, answer)){
            response.put("is", "Y");
        }
        else {
            response.put("is", "N");
        }
        session.getAsyncRemote().sendText(response.toJSONString());
        // 发送给对手
        sendToRival(questionService.isRight(id,answer));
    }

    public void findRival(){
        for (QuestionWebSocket value : clients.values()) {
            if (!PKing.contains(value.userId) && !userId.equals(value.userId)){
                // 改变先来的人
                System.out.println(this.userId);
                System.out.println(value.userId);
                RivalId = value.userId;
                PKing.add(userId);
                PKing.add(value.userId);
                // 改变后来的人
                myThread.stopTask();
                value.RivalId = userId;
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("msg", "SUCCESS");
                jsonObject.put("avatar", userService.getAvatar(value.userId));
                // 匹配成功
                session.getAsyncRemote().sendText(jsonObject.toJSONString());
                jsonObject.put("avatar", userService.getAvatar(userId));
                value.session.getAsyncRemote().sendText(jsonObject.toJSONString());
            }
        }
    }

    public void sendToRival(Boolean right) {
        for (QuestionWebSocket value : clients.values()) {
            if (value.userId.equals(RivalId)) {
                // 同样封装响应，三个字段
                JSONObject jsonObject = new JSONObject();
                String is = right ? "Y" : "N";
                jsonObject.put("is", is);
                jsonObject.put("rival", "Y");
                // 把对方的进程关了
                value.myThread.stopTask();
                value.session.getAsyncRemote().sendText(jsonObject.toJSONString());
            }
        }
    }
}
